/**
 * version  1.3.3
 * author   huangdijia@gmail.com
 * website  http://www.hdj.me
 */
(function($){       
    // 工具类
    var tools       = {
        randomString: function(len){
            len         = len || 32;
            var $chars  = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            var maxPos  = $chars.length;
            var str     = '';
            for (i = 0; i < len; i++) {
                str     += $chars.charAt(Math.floor(Math.random() * maxPos));
        　　}
        　　return str;
        },
        getFileNameFromPath: function(file){
            return file.replace(/.*(\/|\\)/, "");
        },
        getFileExtFromPath: function(file){
            return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
        },
        addEvent: function(el, type, fn){
            if (el.addEventListener) {
                el.addEventListener(type, fn, false);
            } else if (el.attachEvent) {
                el.attachEvent('on' + type, function(){
                    fn.call(el);
                });
            } else {
                throw new Error('not supported or DOM not loaded');
            }
        }
    };
    // iframe上传方法
    $.fn.iframeUpload = function(options) {
        // 默认配置
        var defaults            = {
            action          : 'upload.php',
            name            : 'uploadfile',
            multiple        : false,
            allowTypes      : [],
            data            : {},
            dataType        : 'json',
            onChange        : function(file, extension){},
            onSubmit        : function(file, extension){},
            onComplete      : function(file, response){},
            onError         : function(error){}
        };
        // 配置参数
        options                 = $.extend(defaults, options);
        // 兼容string类型
        options.allowTypes      = (typeof options.allowTypes == "string") ? options.allowTypes.split(',') : options.allowTypes;
        options.dataType        = options.dataType.toLowerCase();
        // 增加labal
        return this.each(function(){
            var $this           = $(this);
            var self            = this;
            // 定义变量
            var random_str      = tools.randomString(10);
            var iframe_name     = "iframe-upload-iframe-"+random_str;
            var form_name       = 'iframe-upload-form-'+random_str;
            var form_action     = $this.attr('action') ? $this.attr('action') : options.action;
            var form_data       = $.extend(options.data, $this.data());
            var input_id        = 'iframe-upload-input-'+random_str;
            var input_name      = $this.attr('name') ? $this.attr('name') : options.name;
            var input_multiple  = $this.attr('multiple') ? $this.attr('multiple') : options.multiple;
            var allow_types     = $this.attr('allowTypes') ? $this.attr('allowTypes').split(',') : [];
            allow_types         = $.merge(options.allowTypes, allow_types);
            // 是否批量上傳
            if(input_multiple){
                input_name      += /\[.*\]$/.test(input_name) ? '' : '[]';
            }
            // 扩展参数
            var data_el         = '';
            $.each(form_data, function(name, value){
                data_el         += '<input type="hidden" name="'+name+'" value="'+value+'" />';
            });
            // 增加form元素
            form                = '<form id="'+form_name+'" name="'+form_name+'" style="display:none" action="'+form_action+'" method="post" enctype="multipart/form-data" target="'+iframe_name+'"><input type="file" id="'+input_id+'" name="'+input_name+'" '+(input_multiple?'multiple="multiple"':'')+' />'+data_el+'<iframe id="'+iframe_name+'" name="'+iframe_name+'" src="javascript:false;"></iframe></form>';
            $('body').append(form);
            // 缓存form
            var $form           = $('#'+form_name);
            // 增加label元素
            $this.wrap('<label for="'+input_id+'"></label>')
            .bind('click', function(){ $form.trigger('reset'); });
            // 监听input change事件
            $form.find('input:file').bind('change', function(){
                var value       = $(this).val();
                var file        = tools.getFileNameFromPath(value);
                var ext         = tools.getFileExtFromPath(value);
                // 检查文件后序
                if(allow_types.length && $.isArray(allow_types) && $.inArray(ext, allow_types)<0){
                    var error   = '不支持.'+ext+'类型';
                    options.onError.call(self, error);
                    return false;
                }
                // 执行onChange方法
                options.onChange && options.onChange.call(self, file, ext);
                // 触发submit事件
                $form.trigger('submit');
            });
            // 监听form submit事件
            $form.bind('submit', function(){
                var value        = $(this).find('input:file:eq(0)').val();
                var file        = tools.getFileNameFromPath(value);
                var ext         = tools.getFileExtFromPath(value);
                // 执行onSubmit方法
                options.onSubmit && options.onSubmit.call(self, file, ext);
            });
            // 监听iframe load事件
            var iframe          = $('#'+iframe_name)[0];
            tools.addEvent(iframe, 'load', function(){
                var value       = $form.find('input:file:eq(0)').val();
                var file        = tools.getFileNameFromPath(value);
                var ext         = tools.getFileExtFromPath(value);
                var doc         = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
                // 兼容Opera 9.26,10.00
                if(doc.readyState && doc.readyState != 'complete'){
                   return;
                }
                // 兼容Opera 9.64
                if(doc.body && doc.body.innerHTML == "false"){
                    return;
                }
                // 获取iframe内容
                var response    = $(iframe).contents().find("body").html();
                if(options.dataType == 'json'){
                    response    = $.parseJSON(response);
                }else if(options.dataType == 'xml'){
                    response    = $.parseXML(response);
                }
                // 执行onComplete回调
                options.onComplete.call(self, file, response);
            });
        });
    };     
})(jQuery);  
